<template>
  <view class="transfer-container">
    <!-- 顶部标题 -->
    <!-- 顶部图片 -->
    <div class="top-image">
      <image src="/static/tabbar/logo.png" mode="aspectFill" />
    </div>

    <!-- 余额信息 -->
    <view class="balance-grid">
      <view class="grid-item">
        <text class="label">SHUC积分余额</text>
        <text class="value">{{ balance }}</text>
      </view>
      <view class="grid-item">
        <text class="label">卡片数量</text>
        <text class="value">{{ cardCount }} 张</text>
      </view>
    </view>

    <!-- 搜索用户 -->
    <view class="search-section">
      <!-- <text class="section-title">搜索用户</text> -->
      <view class="search-box">
        <input type="text" v-model="searchId" placeholder="请输入用户ID" />
        <button class="search-btn" @click="handleSearch">搜索</button>
      </view>
    </view>

    <!-- 用户信息 -->
    <view class="user-info">
      <text class="section-title">对方信息</text>

      <view class="info-row">
        <text class="label">对方昵称</text>
        <text class="value">{{ userName || "未选择" }}</text>
      </view>
      <view class="info-row">
        <text class="label">对方ID</text>
        <text class="value">{{ userId || "未选择" }}</text>
      </view>

      <!-- 转赠数量 -->
      <view class="info-row">
        <text class="label">转赠数量</text>
        <input
          type="number"
          style="width: 250px"
          v-model="amount"
          placeholder="请输入转赠数量"
        />
      </view>

      <view class="info-row">
        <text class="label">单次消耗SHJC积分</text>
        <text class="value">{{ countJifen || "" }}</text>
      </view>

      <view class="info-row">
        <text class="label">单张消耗SHJC积分</text>
        <text class="value">{{ cardCountJiFen || "" }}</text>
      </view>

      <view class="info-row">
        <text class="label">SHJC积分总消耗</text>
        <text class="value">{{ sumCountJiFen || "" }}</text>
      </view>
    </view>

    <!-- 底部按钮 -->
    <button class="submit-btn" @click="handleTransfer">确认转赠</button>

    <text class="reminder"
      >温馨提示：转赠前请确认对方是否存在诈骗嫌疑，用户通过转赠进行违法犯罪行为，后果自行承担！</text
    >
  </view>
</template>

<script>
import authApi from "@/asstes/api/auth";
import goodsApi from "@/asstes/api/goods";

export default {
  name: "Transfer",

  data() {
    return {
      searchId: "",
      userName: "",
      userId: "",
      amount: "",
      balance: "",
      cardCount: "",
      feeList: [],
      countJifen: null,
      cardCountJiFen: null,
      userInfo: {},
      sumCountJiFen: null,
      socket: null,
      messages: []
    };
  },
  watch: {
    amount: function (newVal) {
      console.log("新值:", newVal);
      if (newVal) {
        this.sumCountJiFen =
          (Number(newVal) * Number(this.cardCountJiFen) +Number(this.countJifen)).toFixed(6);

          console.log("sumCountJiFen",this.sumCountJiFen )
      } else {
        this.sumCountJiFen = null;
      }
    },
  },
    async onLoad() {
      try {
        await this.getCurrentUserInfo();
        await this.connectWebSocket();
        this.loading = true;
        const feeRes = await goodsApi.feeList();
        if (feeRes.code === 200 && feeRes.rows.length > 0) {
          this.feeList = feeRes.rows;
          this.countJifen = this.feeList.filter(
            (item) => item.feeType === 0
          )[0].feeAmount;

          this.cardCountJiFen = this.feeList.filter(
            (item) => item.feeType === 1
          )[0].feeAmount;
        }
      } catch (error) {
        console.error("获取手续费列表失败:", error);
        wx.showToast({
          title: "获取手续费列表失败",
          icon: "none",
        });
      } finally {
        this.loading = false;
      }
  },
  onUnload() {
    if (this.socket) {
      this.socket.close();
    }
    if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
  },

  methods: {
    connectWebSocket() {
      // 定时发送心跳
      this.heartbeatTimer = setInterval(() => {
        if (this.socket.readyState === this.socket.OPEN) {
          this.socket.send({
            data: 'ping'
          });
        }
      }, 30000);
      // 动态判断环境（开发环境可能需代理）
      const isDev = process.env.NODE_ENV === 'development';
      const wsUrl = isDev ? 'ws://www.pc.sanhuijucai.com/ws/message' : 'wss://your-domain.com/ws/message';
      
      this.socket = uni.connectSocket({
        url: wsUrl,
        success: () => {
          console.log('WebSocket 连接初始化');
        }
      });

      // 监听事件
      this.socket.onOpen(() => {
        console.log('WebSocket 连接成功');
        // 发送认证信息（若需要）
        this.socket.send({
          data: JSON.stringify({ type: 'auth', token: '用户token' })
        });
      });

      this.socket.onMessage((res) => {
        if (res.data !== "pong") { 
        const message = JSON.parse(res.data);
        console.log("接收到消息：", message)
        if (message.freezeStatus) { 
            console.log("freezeStatus",message.freezeStatus)
            uni.showModal({
              title: "账户异常通知",
              content: `该账户已被冻结，无法进行交易`,
              success: (res) => {
                console.log("res", res);
                if (res.confirm) {  
                  console.log("用户点击确定");
                }
              },
            });
            return
          }
        }
    
      });

      this.socket.onError((err) => {
        console.error('WebSocket 错误:', err);
        // 断线重连
        setTimeout(() => this.connectWebSocket(), 3000);
      });

      this.socket.onClose(() => {
        console.log('WebSocket 连接关闭');
      });
    },
    /**
     * 获取当前用户信息
     */
    async getCurrentUserInfo() {
      try {
        const userInfo = JSON.parse(localStorage.getItem("userInfo"));
        this.userInfo = userInfo;
        console.log("用户信息:", userInfo);
        const data = {
          userId: 0,
          sysUserId: userInfo.userId,
        };
        const response = await authApi.getUserInfo(data);
        console.log("用户信息:", response);
        if (response.code === 200) {
          if (response.user) {
            this.cardCount = response.user.cardCount;
            this.balance = response.user.balance;
            this.userInfo.userId = response.user.userId;
            this.userInfo.status = response.user.status;
          }
        }
      } catch (error) {
        console.error("获取用户信息失败:", error);
        uni.showToast({
          title: "获取用户信息失败",
          icon: "none",
        });
      }
    },
    // 搜索用户
    async handleSearch() {
      if (!this.searchId) {
        uni.showToast({
          title: "请输入用户ID",
          icon: "none",
        });
        return;
      }

      if (this.searchId === this.userInfo.userId) {
        uni.showToast({
          title: "不能转赠给自己",
          icon: "none",
        });
        return;
      }

      try {
        const userRes = await authApi.getUserInfo({
          userId: this.searchId,
          sysUserId: 0,
        });
        if (userRes.code === 200) {
          if (userRes.user) {
            this.userName = userRes.user.username;
            this.userId = userRes.user.userId;
            uni.showToast({
              title: "搜索成功",
              icon: "success",
            });
          } else {
            uni.showToast({
              title: "未查询到用户信息，请检查用户ID是否正确",
              icon: "none",
            });
          }
        }
      } catch (error) {
        console.error("搜索用户失败:", error);
        uni.showToast({
          title: userRes.message,
          icon: "none",
        });
      }
    },

    // 确认转赠
    async handleTransfer() {
      if (!this.userName || !this.userId) {
        uni.showToast({
          title: "请先搜索并选择用户",
          icon: "none",
        });
        return;
      }

      if (!this.amount) {
        uni.showToast({
          title: "请输入转赠数量",
          icon: "none",
        });
        return;
      }

      wx.showModal({
        title: "确认转赠",
        content: `确定要转赠吗？\n温馨提示：转赠前请确认对方是否存在诈骗嫌疑，用户通过转赠进行违法犯罪行为，后果自行承担！`,
        success: (res) => {
          if (res.confirm) {
            this.submitTransfer();
          }
        },
      });
    },

    async submitTransfer() {
      if (!this.userInfo) {
        wx.showToast({
          title: "用户信息获取失败，请重新登录",
          icon: "none",
        });
        uni.navigateTo({
          url: "/pages/login/index",
        });
        return;
      }

      console.log("userInfo:", this.userInfo);

      try {
        const data = {
          userId: this.userInfo.userId,
          transferId: this.userId,
          cardNumber: Number(this.amount),
          accountNumber: this.sumCountJiFen,
          status: this.userInfo.status,
        };

        const res = await goodsApi.transfer(data);
        console.log("转赠结果:", res);
        if (res.code === 200) {
          uni.showToast({
            title: "转赠成功",
            icon: "success",
          });
          // 重置表单
          this.resetForm();
          this.getCurrentUserInfo();
          return;
        }
        uni.showToast({
          title: data.message || "转赠失败",
          icon: "none",
        });
      } catch (error) {
        console.error("转赠失败:", error);
        uni.showToast({
          title: error.msg || "转赠失败",
          icon: "none",
        });
        return;
      }
    },

    // 重置表单
    resetForm() {
      this.searchId = "";
      this.userName = "";
      this.userId = "";
      this.amount = "";
    },
  },
};
</script>

<style lang="scss">
.transfer-container {
  /*min-height: 100vh;*/
  background: #fff;
  padding: 40rpx 30rpx;
}

.top-image {
  width: 100px;
  height: 100px;
  margin: 0px auto;
  display: flex;
  justify-content: center;
  align-items: center;
}

.top-image image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.header {
  margin-bottom: 60rpx;

  .title {
    font-size: 44rpx;
    color: #333;
    font-weight: 500;
  }
}

.balance-grid {
  display: flex;
  border: 1px solid #eee;
  margin-bottom: 40rpx;

  .grid-item {
    flex: 1;
    padding: 30rpx;
    text-align: center;

    &:first-child {
      border-right: 1px solid #eee;
    }

    .label {
      font-size: 26rpx;
      color: #999;
      margin-bottom: 16rpx;
      display: block;
    }

    .value {
      font-size: 32rpx;
      color: #333;
      font-weight: 500;
    }
  }
}

.section-title {
  font-size: 30rpx;
  color: #333;
  margin: 20rpx;
  display: block;
  font-weight: bold;
}

.search-section {
  margin-bottom: 40rpx;

  .search-box {
    display: flex;
    gap: 20rpx;

    input {
      flex: 1;
      height: 88rpx;
      border: 1px solid #eee;
      padding: 0 30rpx;
      font-size: 28rpx;
    }

    .search-btn {
      width: 160rpx;
      height: 88rpx;
      line-height: 88rpx;
      background: #333;
      color: #fff;
      font-size: 28rpx;
      border: 1px solid #fff;

      &:active {
        background: #fff;
        color: #333;
      }
    }
  }
}

.user-info,
.amount-section {
  margin-bottom: 60rpx;
  border: 1px solid #eee;

  .info-row {
    margin: 20rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1px solid #eee;

    .label {
      color: #333;
      font-size: 28rpx;
      // margin-bottom: 16rpx;
    }

    .value {
      color: #999;
      font-size: 28rpx;
    }
  }

  input {
    width: 100%;
    height: 88rpx;
    border: 1px solid #eee;
    padding: 0 30rpx;
    font-size: 28rpx;
  }
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  background: #333;
  color: #fff;
  font-size: 32rpx;
  border: 1px solid #fff;
  margin-top: 60rpx;
  margin-bottom: 60rpx;
  transition: all 0.3s;

  &:active {
    background: #fff;
    color: #333;
  }
}

.reminder {
  margin-top: 40rpx;
  color: #d9534f;
  font-size: 30rpx;
  line-height: 1.5;
  text-align: center;
}
</style>
